package com.yanqu.road.server.manager.activity.apprentice.handler.impl;

import com.yanqu.road.entity.activity.apprentice.ApprenticeBanquetResult;
import com.yanqu.road.entity.activity.apprentice.ApprenticeEffectBuffProject;
import com.yanqu.road.entity.activity.apprentice.ApprenticeTalentData;
import com.yanqu.road.entity.activity.apprentice.config.ApprenticeConfig;
import com.yanqu.road.entity.activity.apprentice.config.ApprenticeLevelConfig;
import com.yanqu.road.entity.activity.apprentice.config.ApprenticeProjectConfig;
import com.yanqu.road.entity.activity.apprentice.data.ApprenticeBuffProjectData;
import com.yanqu.road.entity.activity.apprentice.data.ApprenticeUserBanquetLog;
import com.yanqu.road.entity.activity.apprentice.data.ApprenticeUserData;
import com.yanqu.road.entity.activity.apprentice.enums.ApprenticeProjectIdEnum;
import com.yanqu.road.entity.activity.apprentice.enums.ApprenticeProjectSortEnum;
import com.yanqu.road.entity.log.cross.apprentice.LogCrossApprenticeProjectEvent;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.pb.activity.ApprenticeProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.apprentice.CrossApprenticeActivity;
import com.yanqu.road.server.manager.activity.apprentice.handler.ApprenticeProjectHandler;
import com.yanqu.road.server.manager.activity.apprentice.handler.param.*;
import com.yanqu.road.server.manager.activity.apprentice.pb.ApprenticePb;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class ApprenticeDoProjectType10Handler implements ApprenticeProjectHandler {

    /**
     * 宴请世家
     * @param req
     * @return
     */
    @Override
    public ApprenticeDoProjectResp doProject(ApprenticeDoProjectReq req) {
        ApprenticeProjectConfig projectConfig = req.getProjectConfig();
        CrossApprenticeActivity activity = req.getActivity();
        ApprenticeConfig config = activity.getConfig();
        ApprenticeUserData userData = req.getUserData();
        Map<Integer, Integer> talentAddRateMap = req.getTalentAddRateMap();
        Map<Integer, Integer> sortAddRateMap = req.getSortAddRateMap();
        ApprenticeLevelConfig levelConfig = activity.getConfig().getLevelConfig(userData.getLevel());
        if (levelConfig == null) {
            return null;
        }
        //判断是否有BUFF
        boolean isHaveBuff = false;
        for (ApprenticeBuffProjectData buffProjectData : userData.getBuffProjectIds()) {
            if (buffProjectData.getProjectId() == ApprenticeProjectIdEnum.PROJECT_ID_10044.getId() && buffProjectData.getNum() > 0) {
                isHaveBuff = true;
                buffProjectData.addNum(-1);
                break;
            }
        }
        if (!isHaveBuff) {
            return null;
        }
        //获取同商会玩家
        if (StringUtils.isNullOrEmpty(userData.getUnionId())) {
            return null;
        }
        //获取可被宴请的商会玩家MAP
        Map<Long, ApprenticeUserData> unionUserMap = activity.getCanBeBanquetUserMap(userData);
        if (unionUserMap == null || unionUserMap.isEmpty()) {
            unionUserMap = activity.getUnionUserMap(userData.getUnionId());
        }
        Map<Long, ApprenticeUserData> randomUnionUserMap = new HashMap<>(unionUserMap);
        randomUnionUserMap.remove(userData.getUserId());
        //随机一个玩家
        Long randomUserId = RandomHelper.getRandomElement(randomUnionUserMap.keySet());
        if (randomUserId == null) {
            return null;
        }
        ApprenticeUserData targetUserData = randomUnionUserMap.get(randomUserId);
        UserBaseInfo randomBaseInfo = CrossUserMgr.getUserBaseInfo(randomUserId);
        if (randomBaseInfo == null) {
            return null;
        }
        //我方发起宴请次数+1，我方可被邀请次数+1，对方可被邀请次数-1
        userData.setStartBanquetNum(userData.getStartBanquetNum() + 1);
        userData.setCanBeBanquetNum(userData.getCanBeBanquetNum() + config.getAPPRENTICE_BANQUET_FAMILY_PARAM().get(1));
        targetUserData.setCanBeBanquetNum(targetUserData.getCanBeBanquetNum() - config.getAPPRENTICE_BANQUET_FAMILY_PARAM().get(2));
        //双方都加天资
        long addTalent = Long.parseLong(projectConfig.getParam());
        //随机天资类型
        int talentType = new Random().nextInt(5) + 1;
        //计算我方天资
        long myAddTalentValue = activity.countTalentValue(talentType, ApprenticeProjectSortEnum.SORT_TYPE_0.getType(), addTalent, talentAddRateMap, sortAddRateMap, levelConfig.getConsume());
        //加天资
        ApprenticeTalentData myAddTalent = userData.addTalent(talentType, myAddTalentValue, true);
        ApprenticeTalentData targetAddTalent = targetUserData.addTalent(talentType, addTalent, true);
        //同步对方区服，玩家维度天资增加
        ApprenticeProto.ApprenticeSyncUserTalentChangeCrossMsg.Builder respMsg = ApprenticeProto.ApprenticeSyncUserTalentChangeCrossMsg.newBuilder();
        respMsg.setTalentData(ApprenticePb.buildTalentData(targetAddTalent));
        respMsg.setActivityId(activity.getActivityId());
        respMsg.setAllTalent(targetUserData.getAllTalent());
        MessageHelper.sendPacket(randomBaseInfo.getServerId(), randomUserId, YanQuMessageUtils.buildMessage(Protocol.S_APPRENTICE_USER_TALENT_CHANGE_FROM_CROSS, respMsg));
        //日志
        ApprenticeUserBanquetLog banquetLog = new ApprenticeUserBanquetLog(
                userData.getUserId(),
                targetUserData.getUserId(),
                myAddTalent,
                targetAddTalent
        );
        userData.addBanquetLog(banquetLog);//我方加日志
        targetUserData.addBanquetLog(banquetLog);//对方加日志
        //同步一下对方
        activity.syncUserData(targetUserData.getUserId());
        //日志
        LogCrossApprenticeProjectEvent log = new LogCrossApprenticeProjectEvent(
                userData.getActivityId(),
                userData.getUserId(),
                userData.getProgramNum(),
                String.valueOf(ApprenticeProjectIdEnum.PROJECT_ID_10027.getId()),
                targetUserData.getUserId(),
                1,
                myAddTalent.talentToString()
        );
        CrossAutoLogMgr.add(log);
        //生效buff结果结果集注入
        List<ApprenticeEffectBuffProject> effectBuffProjects = req.getEffectBuffProjects();
        ApprenticeEffectBuffProject effectBuffProject = new ApprenticeEffectBuffProject(projectConfig.getId());
        effectBuffProjects.add(effectBuffProject);
        //返回
        ApprenticeBanquetResult result = new ApprenticeBanquetResult();
        result.setTargetUserName(randomBaseInfo.getNickName());
        result.setMyAddTalent(myAddTalent);
        result.setTargetAddTalent(targetAddTalent);
        result.setTargetUserLevel(targetUserData.getLevel());
        result.setAddRate(talentAddRateMap.getOrDefault(talentType, 0) + sortAddRateMap.getOrDefault(ApprenticeProjectSortEnum.SORT_TYPE_0.getType(), 0));
        ApprenticeDoProjectResp resp = new ApprenticeDoProjectResp();
        resp.setBanquetResult(result);
        return resp;
    }

    @Override
    public void countTalentTypeAddRate(ApprenticeCountTalentAddRateReq req) {

    }

    @Override
    public void countSortTypeAddRate(ApprenticeCountSortAddRateReq req) {

    }
}
